import 'dart:async';
import 'dart:math';
import 'package:get/get.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:speed_random/common/common_fuc.dart';
import 'package:speed_random/global_data.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:vibration/vibration.dart';

import 'state.dart';

class SpinBottleLogic extends GetxController {
  final SpinBottleState state = SpinBottleState();
  final player = AudioPlayer();
  Timer? _rotationTimer;
  Timer? _stopTimer;
  var cachekey = '';

  @override
  void onInit() {
    super.onInit();
    cachekey=state.randComArgs.value.cachekey;

    initCache();
  }
  // 初始化缓存
  Future<void> initCache() async {
    final prefs = await SharedPreferences.getInstance();
    state.min.value = prefs.getInt(cachekey+'min') ?? 0;
    state.max.value = prefs.getInt(cachekey+'max') ?? 100;
    state.count.value = prefs.getInt(cachekey+'count') ?? 1;
    state.randomNumbersSum.value = prefs.getInt(cachekey+'randomNumbersSum') ?? 0;
    state.isRepeatable.value = prefs.getBool(cachekey+'isRepeatable') ?? false;
    // 新增初始化缓存
    state.scrollTime.value = prefs.getInt(cachekey+'scrollTime') ?? 3;

    state.isManualStop.value = prefs.getBool('isManualStop') ?? true;
    state.isSoundEnabled.value = prefs.getBool('isSoundEnabled') ?? true;
    state.isVibrationEnabled.value = prefs.getBool('isVibrationEnabled') ?? true;

    state.isShowSum.value = prefs.getBool(cachekey+'isShowSum') ?? false;
    state.isadd0.value = prefs.getBool(cachekey+'isadd0') ?? false;

    // 读取随机数列表
    final List<String>? stringNumbers = prefs.getStringList(cachekey+'randomNumbers');
    if (stringNumbers != null) {
      state.randomNumbers.value = stringNumbers;
    } else {
      state.randomNumbers.value = [];
    }
  }

  void setSave(int min, int max, int count, bool isRepeatable, int scrollTime, bool isManualStop, bool isSoundEnabled, bool isVibrationEnabled) {
    if (min > max) {
      int temp = min;
      min = max;
      max = temp;
    }
    if (count < 1) {
      count = 1;
    }
    if (count > 10) {
      count = 10;
    }
    if (min < 0) {
      min = 0;
    }
    if (max > 99999) {
      max = 99999;
    }
    // 限制滚动时间范围
    scrollTime = scrollTime.clamp(1, 9);
    state.min.value = min;
    state.max.value = max;
    state.count.value = count;
    state.isRepeatable.value = isRepeatable;
    state.scrollTime.value = scrollTime;
    state.isManualStop.value = isManualStop;
    state.isSoundEnabled.value = isSoundEnabled;
    state.isVibrationEnabled.value = isVibrationEnabled;
    //state.randomNumbers.value = [];
    saveToCache();
  }

  void setRepeatable(bool isRepeatable) {
    state.isRepeatable.value = isRepeatable;
  }

  // 保存到缓存
  Future<void> saveToCache() async {
    final prefs = await SharedPreferences.getInstance();
    prefs.setInt(cachekey+'min', state.min.value);
    prefs.setInt(cachekey+'max', state.max.value);
    prefs.setInt(cachekey+'count', state.count.value);
    prefs.setBool(cachekey+'isRepeatable', state.isRepeatable.value);
    // 新增保存到缓存
    prefs.setInt(cachekey+'scrollTime', state.scrollTime.value);
    prefs.setBool('isManualStop', state.isManualStop.value);
    prefs.setBool('isSoundEnabled', state.isSoundEnabled.value);
    prefs.setBool('isVibrationEnabled', state.isVibrationEnabled.value);
    prefs.setBool(cachekey+'isShowSum', state.isShowSum.value);
    prefs.setBool(cachekey+'isadd0', state.isadd0.value);
  }
  void startRotation() {
    state.isRun.value = 1;
    if (state.isSoundEnabled.value) {
      commonFuc.playMp3(path: globalData.soundPath);
    }
    // 开始旋转动画
    _rotationTimer = Timer.periodic(Duration(milliseconds: 2), (timer) {

      state.rotationAngle.value += 0.1;
      if (state.isRun.value != 1) {
        stopRotation();
      }
    });

    if (!state.isManualStop.value) {
      // 定时停止
      _stopTimer = Timer(Duration(seconds: state.scrollTime.value), () {
        stopRotation();
      });
    }

  }

  void stopRotation()  async{
    _rotationTimer?.cancel();
    _stopTimer?.cancel();
    state.isRun.value = 2;
    // 立即停止播放音乐
    if (state.isSoundEnabled.value) {
      commonFuc.playMp3(path: globalData.soundSuccessPath);
    }
   // _playSound();
    // 震动提示
    if (state.isVibrationEnabled.value && await Vibration.hasVibrator() ?? false) {
    Vibration.vibrate(duration: 50);
    }
  }


  @override
  void onClose() {
    _rotationTimer?.cancel();
    _stopTimer?.cancel();
    player.dispose();
    super.onClose();
  }
}
